﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using KingRoad.EPM.Web.Areas.PersonnelLog.ViewModels;
using KingRoad.EPM.Web.Areas.PersonnelLog.PersonnelLogFramework.Common;
using System.Dynamic;
using KingRoad.EPM.PersonnelLogEntity.Model;

namespace KingRoad.EPM.Web.Areas.PersonnelLog.Controllers
{
    public class PlmTurnoverCheckController : BaseController
    {
        /// <summary>
        /// 人员变动审核列表
        /// </summary>
        /// <returns></returns>
        public ActionResult TurnoverCheckList()
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            List<PlmTurnoverInfo> turnoverList = PlmTurnoverUIRule.GetAllCostplanmainForPage(ViewBag.pageNum, ViewBag.numPerPage, "T_DeclarationDate", out totalRecord, "");
            foreach (var item in turnoverList)
            {
                var type = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(Guid.Parse(item.T_Type));
                item.T_Type = type.Scd_Name;
                var position = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(Guid.Parse(item.T_Position));
                item.T_Position = position.Scd_Name;
            }
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;

            return View(new PlmTurnoverViewModel { ThePlmTurnoverInfoList = turnoverList });
        }
        /// <summary>
        /// 人员变动审核
        /// </summary>
        /// <returns></returns>
        public ActionResult TurnoverCheckAudit(Guid id)
        {
            var turnoverLInfo = PlmTurnoverUIRule.GetPlmTurnoverInfoByID(id);
            List<SelectListItem> listState = new List<SelectListItem>();
            listState.Add(new SelectListItem { Text = "通过", Value = "通过" });
            listState.Add(new SelectListItem { Text = "驳回", Value = "驳回" });
            ViewBag.listState = listState;

            return View(new PlmTurnoverViewModel { ThePlmTurnoverInfoInfo = turnoverLInfo });
        }
        /// <summary>
        /// 人员变动审核详情
        /// </summary>
        /// <returns></returns>
        public ActionResult TurnoverCheckDetail(Guid id)
        {
            var turnoverLInfo = PlmTurnoverUIRule.GetPlmTurnoverInfoByID(id);

            var type = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(Guid.Parse(turnoverLInfo.T_Type));
            turnoverLInfo.T_Type = type.Scd_Name;
            var position = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(Guid.Parse(turnoverLInfo.T_Position));
            turnoverLInfo.T_Position = position.Scd_Name;

            return View(new PlmTurnoverViewModel { ThePlmTurnoverInfoInfo = turnoverLInfo });
        }

        /// <summary>
        /// 职位人员记录管理
        /// </summary>
        /// <returns></returns>
        public ActionResult PersonnelRecordIndex()
        {
            return View();
        }


        /// <summary>
        /// 职位人员记录列表
        /// </summary>
        /// <returns></returns>
        public ActionResult PersonnelRecordList(string Scd_ID, string Section)
        {
            string sql = "";
            if (Scd_ID!=null)
            {
                ViewBag.Post = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(new Guid(Scd_ID)).Scd_Name;
                sql = "Pi_Post='" + ViewBag.Post + "' and Pi_SectionName ='" + Section + "'";
            }
            else
            {
                sql = " Pi_SectionName  ='" + Section + "'";
            }
            
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            ViewBag.Section = Section;
            #region 职位列表
            ViewBag.listSuper = "";
            List<ScmSafetyconstructiondicInfo> Positionlist = new List<ScmSafetyconstructiondicInfo>();
            if (Section.Contains("JC"))
            {
                //获取检测单位职位
                Positionlist = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByPID("4AF2BCB9-D68B-4375-A770-9F6C85325C14");

            }
            else if (Section.Contains("ZJ"))
            {
                //获取总监办职位
                Positionlist = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByPID("4AF2BCB9-D68B-4375-A770-9F6C85325C15");

            }
            else
            {   //获取驻地办职位
                Positionlist = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByPID("4AF2BCB9-D68B-4375-A770-9F6C85325C16");

            }
            #region 增加默认值
            var selectItemList = new List<ScmSafetyconstructiondicInfo>() { 
                new ScmSafetyconstructiondicInfo(){Scd_Code=null,Scd_Name="全部",Selected=true}
            };
            selectItemList.AddRange(Positionlist);

            ViewBag.listSuper = selectItemList;
            #endregion
            #endregion
            var consPersonnelList = PlmPersonnelinforecordUIRule.GetAllCostplanmainForPage(ViewBag.pageNum, ViewBag.numPerPage, "Pi_InTime", out totalRecord, sql);
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View(new PlmTurnoverViewModel { ThePersonnelRecordList = consPersonnelList });
        }
        /// <summary>
        /// 职位记录分页
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        public ActionResult SplitPageByPost(PlmTurnoverViewModel vm)
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);


            ViewBag.Post = vm.ThePersonnelRecordInfo.Pi_Post;
            ViewBag.Section = Request.Form["input_section"];

            string sql = " Pi_SectionName ='" + ViewBag.Section + "' ";
            if (ViewBag.Post != "全部")
                sql += " and Pi_Post = '" + ViewBag.Post + "' ";

            #region 职位列表
            ViewBag.listSuper = "";
            List<ScmSafetyconstructiondicInfo> Positionlist = new List<ScmSafetyconstructiondicInfo>();
            if (ViewBag.Section.Contains("JC"))
            {
                //获取检测单位职位
                Positionlist = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByPID("4AF2BCB9-D68B-4375-A770-9F6C85325C14");

            }
            else if (ViewBag.Section.Contains("ZJ"))
            {
                //获取总监办职位
                Positionlist = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByPID("4AF2BCB9-D68B-4375-A770-9F6C85325C15");

            }
            else
            {   //获取驻地办职位
                Positionlist = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByPID("4AF2BCB9-D68B-4375-A770-9F6C85325C16");

            }
            #region 增加默认值
            var selectItemList = new List<ScmSafetyconstructiondicInfo>() { 
                new ScmSafetyconstructiondicInfo(){Scd_Code=null,Scd_Name="全部",Selected=true}
            };
            selectItemList.AddRange(Positionlist);

            ViewBag.listSuper = selectItemList;
            #endregion
            #endregion

            var recordlist = PlmPersonnelinforecordUIRule.GetAllCostplanmainForPage(ViewBag.pageNum, ViewBag.numPerPage, "Pi_InTime", out totalRecord, sql);

            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("PersonnelRecordList", new PlmTurnoverViewModel { ThePersonnelRecordList = recordlist });
        }
        public JsonResult SaveCheckResult(PlmTurnoverViewModel vm)
        {
            var isScuess = TryCatchCommand.TryExec(() =>
            {
                vm.ThePlmTurnoverInfoInfo.T_ApprovalTime = DateTime.Now;
                int turnoverInfo = PlmTurnoverUIRule.UpdatePlmTurnoverInfo(vm.ThePlmTurnoverInfoInfo);

                var postList = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(Guid.Parse(vm.ThePlmTurnoverInfoInfo.T_Position));//根据审核列表中的职位名称，在字典表中获取对应的Guid
                var personlList = PlmPersonnelinfoUIRule.GetAllPersonnelinfo(" Pi_Post='" + postList.Scd_Name + "' and Pi_Name='" + vm.ThePlmTurnoverInfoInfo.T_ExistingStaff + "' and Pi_SectionID='" + vm.ThePlmTurnoverInfoInfo.T_SectionID + "' ");//根据审核列表标段ID、现职人员姓名,及上述过程获取的职位Guid确定人员表中的唯一人（表关系存在缺陷，只能以此方式获取较为准确数据）
                var changeList = PlmPersonnelinfoUIRule.GetAllPersonnelinfo(" Pi_Name='" + vm.ThePlmTurnoverInfoInfo.T_ChangePersonnel + "' and Pi_SectionID='" + vm.ThePlmTurnoverInfoInfo.T_SectionID + "' ");
                var plm = new PlmPersonnelinfoViewModel();
                if (personlList != null)
                {

                    plm.ThePersonnelinfoInfo = PlmPersonnelinfoUIRule.GetPersonnelinfoByID(Guid.Parse(personlList[0].Pi_ID));
                    plm.ThePersonnelinfoInfo.Pi_Post = "其它人员";
                    int postInfo = PlmPersonnelinfoUIRule.UpdatePersonnelinfo(plm.ThePersonnelinfoInfo);//更新现职人员职位信息
                    //修改记录 离职日期
                    var pir = PlmPersonnelinforecordUIRule.GetAllPersonnelinfo(" Pi_Name='" + plm.ThePersonnelinfoInfo.Pi_Name + "' and Pi_SectionID='" + plm.ThePersonnelinfoInfo.Pi_SectionID + "' and Pi_Post='" + postList.Scd_Name + "' ").FirstOrDefault();
                    if (pir != null)
                    {
                        pir.Pi_OutTime = DateTime.Now;
                        int pirrecord = PlmPersonnelinforecordUIRule.UpdatePersonnelinfo(pir);
                    }
                    plm.ThePersonnelinfoInfo = PlmPersonnelinfoUIRule.GetPersonnelinfoByID(Guid.Parse(changeList[0].Pi_ID));
                    var pirchange = PlmPersonnelinforecordUIRule.GetAllPersonnelinfo(" Pi_Name='" + vm.ThePlmTurnoverInfoInfo.T_ChangePersonnel + "' and Pi_SectionID='" + vm.ThePlmTurnoverInfoInfo.T_SectionID + "' and Pi_Post='" + plm.ThePersonnelinfoInfo.Pi_Post + "' ").FirstOrDefault();
                    plm.ThePersonnelinfoInfo.Pi_Post = postList.Scd_Name;
                    int changeInfo = PlmPersonnelinfoUIRule.UpdatePersonnelinfo(plm.ThePersonnelinfoInfo);//更新变更人员职位信息

                    //在记录表里把变更人员离职

                    if (pirchange != null)
                    {
                        pirchange.Pi_OutTime = DateTime.Now;
                        int pirpirchangerecord = PlmPersonnelinforecordUIRule.UpdatePersonnelinfo(pirchange);

                        //在记录表里增加一条新纪录(变更人的新岗位记录)
                        pirchange.Pi_ID = Guid.NewGuid().ToString();
                        pirchange.Pi_Post = postList.Scd_Name;
                        pirchange.Pi_InTime = DateTime.Now;
                        pirchange.Pi_OutTime = null;

                        int saferecord = PlmPersonnelinforecordUIRule.AddPersonnelinfo(pirchange);
                    }
                    else
                    {
                        //在记录表里增加一条新纪录(变更人的新岗位记录)
                        PlmPersonnelinforecordInfo ppri = new PlmPersonnelinforecordInfo();
                        ppri.Pi_ID = Guid.NewGuid().ToString();
                        ppri.Pi_Name = vm.ThePlmTurnoverInfoInfo.T_ChangePersonnel;
                        ppri.Pi_SectionID = vm.ThePlmTurnoverInfoInfo.T_SectionID;
                        ppri.Pi_SectionName = vm.ThePlmTurnoverInfoInfo.T_SectionName;
                        ppri.Pi_UnitID = vm.ThePlmTurnoverInfoInfo.T_UnitID;
                        ppri.Pi_UnittName = vm.ThePlmTurnoverInfoInfo.T_UnitName;
                        ppri.Pi_UpdateTime = vm.ThePlmTurnoverInfoInfo.T_UpdateTime;
                        ppri.Pi_Post = postList.Scd_Name;
                        ppri.Pi_InTime = DateTime.Now;
                        ppri.Pi_OutTime = null;

                        int saferecord = PlmPersonnelinforecordUIRule.AddPersonnelinfo(ppri);
                    }
                }
            });
            dynamic jsonReturn = new ExpandoObject();

            //保存成功
            if (isScuess)
            {
                jsonReturn = new
                {
                    statusCode = "200",
                    message = "审核成功",
                    navTabId = "PersonnelLog.PlmTurnover.TurnoverList",
                    rel = "",
                    callbackType = "closeCurrent",
                    forwardUrl = "",
                    confirmMsg = ""
                };
            }
            else
            {
                jsonReturn = new
                {
                    statusCode = "300",
                    message = "审核失败",
                };
            }

            return new JsonResult()
            {
                Data = jsonReturn
            };

        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="vm"></param>
        /// <returns></returns>
        public ActionResult SplitPage(PlmTurnoverViewModel vm)
        {
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            ViewBag.name = Request.Form["name"];
            ViewBag.reporttime = Request.Form["reporttime"];
            ViewBag.sectionname = Request.Form["sectionname"];
            ViewBag.positionname = Request.Form["positionname"];

            string sql = " 1=1 ";
            if (ViewBag.sectionname != "")
                sql += " and T_SectionName like '%" + ViewBag.sectionname + "%' ";
            if (ViewBag.positionname != "")
                sql += " and T_Position in (select scd_id from Scm_SafetyConstructionDic where scd_name like '%" + ViewBag.positionname + "%' ) ";
            if (ViewBag.reporttime != "")
                sql += " and T_DeclarationDate = '" + ViewBag.reporttime + "' ";
            if (ViewBag.name != "")
            {
                sql += "and T_ExistingStaff = '" + ViewBag.name + "' or T_ChangePersonnel = '" + ViewBag.name + "'  ";
            }


            var turnover = PlmTurnoverUIRule.GetAllCostplanmainForPage(ViewBag.pageNum, ViewBag.numPerPage, "T_DeclarationDate", out totalRecord, sql);
            foreach (var item in turnover)
            {
                var type = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(Guid.Parse(item.T_Type));
                item.T_Type = type.Scd_Name;
                var position = ScmSafetyconstructiondicUIRule.GetSafetyconstructiondicByID(Guid.Parse(item.T_Position));
                item.T_Position = position.Scd_Name;
            }
            //总条数
            ViewBag.totalcount = totalRecord;
            //总页数
            ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            return View("TurnoverCheckList", new PlmTurnoverViewModel { ThePlmTurnoverInfoList = turnover });
        }
    }
}
